<template>
  <div>
    <div class="header_search_nav search_form">
      <div class="ipt_left">
        <el-form ref="queryForm" :model="queryParams" label-width="80px">
          <el-row>
            <el-col :span="6">
              <div class="timebox">
                <el-form-item label="月份" prop="performanceMoon">
                  <el-date-picker
                    v-model="queryParams.performanceMoon"
                    type="month"
                    placeholder="选择"
                    value-format="yyyy-MM"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户" prop="userId">
                <el-select
                  v-model="queryParams.userId"
                  placeholder="请选择"
                  filterable
                  remote
                  clearable
                  :loading="userIdLoading"
                  :remote-method="remoteMethod"
                  reserve-keyword
                >
                  <el-option
                    v-for="item in userIdList"
                    :key="item.id"
                    :label="item.nickname"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="btn_right">
        <button class="btn1" @click="handleQuery">筛选</button>
        <button class="btn2" @click="resetQuery">重置</button>
      </div>
    </div>
    <div class="table_card">
      <div class="table_card_top">
        <span class="solid_left"></span>
        <div class="table_card_title">店长绩效考核</div>
        <div class="op_right">
          <button class="primary_button" @click="NewUser">新增绩效考核</button>
          <button class="primary_button" @click="DownloadTemplate">
            下载考核模板
          </button>
          <button class="primary_button" @click="ImportTemplate">
            导入考核模板
          </button>
        </div>
      </div>

      <div class="table_list">
        <el-table :data="categoryList" stripe style="width: 100%">
          <el-table-column prop="nickname" label="用户昵称"> </el-table-column>
          <el-table-column prop="deptName" label="部门名称"> </el-table-column>
          <el-table-column prop="performanceMoon" label="月份">
          </el-table-column>
          <el-table-column
            prop="performanceOnline"
            label="线上转化率"
            width="150px"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.performanceOnline }}%</div>
            </template>
          </el-table-column>
          <el-table-column prop="performanceMt" label="美团综合好评率">
            <template slot-scope="scope">
              <div>{{ scope.row.performanceMt }}%</div>
            </template>
          </el-table-column>
          <el-table-column prop="performanceBy" label="抖音好评率">
            <template slot-scope="scope">
              <div>{{ scope.row.performanceBy }}%</div>
            </template>
          </el-table-column>
          <el-table-column prop="performanceBad" label="综合差评率">
            <template slot-scope="scope">
              <div>{{ scope.row.performanceBad }}%</div>
            </template>
          </el-table-column>
          <el-table-column prop="performanceHire" label="自招">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="edit(scope.row)"
                >编辑</el-button
              >

              <el-button size="mini" type="text" @click="DelUser(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>

      <!-- 新建 -->
      <el-dialog
        :visible.sync="categoryVisible"
        width="600px"
        :title="title"
        class="no-dialog-padding"
        @close="Canceluser"
      >
        <span>
          <div class="source_box">
            <el-form
              :model="PerformanceForm"
              :rules="CategoryRules"
              ref="PerformanceForm"
              label-width="130px"
              class="demo-ruleForm"
            >
              <el-form-item label="用户" prop="userId">
                <el-select
                  v-model="PerformanceForm.userId"
                  placeholder="请选择"
                  filterable
                  remote
                  clearable
                  :loading="userIdLoading"
                  :remote-method="remoteMethod"
                  reserve-keyword
                  class="w-100"
                >
                  <el-option
                    v-for="item in userIdList"
                    :key="item.id"
                    :label="item.nickname"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="月份" prop="performanceMoon">
                <el-date-picker
                  v-model="PerformanceForm.performanceMoon"
                  type="month"
                  placeholder="选择"
                  value-format="yyyy-MM"
                  class="up_ipt text-left w-100"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="线上转化率" prop="performanceOnline">
                <el-input-number
                  placeholder="请输入"
                  v-model="PerformanceForm.performanceOnline"
                  class="up_ipt text-left w-100"
                  :precision="2"
                  :min="0"
                  :max="1000000"
                  :controls="false"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="美团综合好评率" prop="performanceMt">
                <el-input-number
                  placeholder="请输入"
                  v-model="PerformanceForm.performanceMt"
                  class="up_ipt text-left w-100"
                  :precision="2"
                  :min="0"
                  :max="100000000"
                  :controls="false"
                ></el-input-number>
              </el-form-item>

              <el-form-item label="综合差评率" prop="performanceBad">
                <el-input-number
                  placeholder="请输入"
                  v-model="PerformanceForm.performanceBad"
                  class="up_ipt text-left w-100"
                  :precision="2"
                  :min="0"
                  :max="1000000"
                  :controls="false"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="抖音好评率" prop="performanceBy">
                <el-input-number
                  placeholder="请输入"
                  v-model="PerformanceForm.performanceBy"
                  class="up_ipt text-left w-100"
                  :precision="2"
                  :min="0"
                  :max="1000000"
                  :controls="false"
                ></el-input-number>
              </el-form-item>

              <el-form-item label="自招" prop="performanceHire">
                <el-input-number
                  placeholder="请输入"
                  v-model="PerformanceForm.performanceHire"
                  class="up_ipt text-left w-100"
                  :precision="2"
                  :min="0"
                  :max="1000000"
                  :controls="false"
                ></el-input-number>
              </el-form-item>
            </el-form>
          </div>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button class="cancel_btn" @click="Canceluser">取 消</el-button>
          <el-button
            type="primary"
            @click="userSubmit"
            :loading="CreateClienLoading"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 导入绩效考核 -->
      <el-dialog
        title="导入绩效考核"
        :visible.sync="upload.open"
        width="400px"
        append-to-body
      >
        <div v-loading="timeSetLoading || upload.isUploading">
          <el-upload
            ref="upload"
            :limit="1"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :auto-upload="false"
            name="file"
            :data="{}"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>

            <div class="el-upload__tip" slot="tip"></div>
          </el-upload>

          <div class="model-height">
            <el-form
              ref="uploadForm"
              size="mini"
              label-width="90px"
              :model="uploadForm"
              :rules="uploadRules"
              @submit.native.prevent
            >
              <!-- <el-form-item label="月份" prop="moon">
                  <el-date-picker
                    class="w-100"
                    v-model="uploadForm.moon"
                    type="month"
                    placeholder="选择月"
                    value-format="yyyy-MM"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="是否修改" prop="editStatus">
                  <div class="max-width-300">
                    <el-radio-group v-model="uploadForm.editStatus">
                      <el-radio label="N">新增</el-radio>
                      <el-radio label="Y">修改</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item> -->
            </el-form>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :loading="timeSetLoading || upload.isUploading"
            @click="submitFileForm"
            >确 定</el-button
          >
          <el-button @click="uploadClose">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getPerformancePage,
  CreatePerformancePage,
  UpdatePerformancePage,
  getPerformancePageInfo,
  delPerformancePage,
  DownTemplate,
  getFinishState,
  ImportFinishDown,
} from "@/api/bpm/assessIndex";
import { getBaseHeader } from "@/utils/request";
import { listUser } from "@/api/system/user";

export default {
  name: "EryuoaStoreCategoryList",
  data() {
    return {
      PerformanceForm: {
        userId: "",
        performanceId: "",
        performanceMoon: "",
        performanceOnline: "",
        performanceMt: "",
        performanceBad: "",
        performanceBy: "",
        performanceHire: "",
      },
      CategoryRules: {
        userId: [{ required: true, message: "请选择", trigger: "change" }],
        performanceMoon: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        performanceOnline: [
          { required: true, message: "请输入", trigger: "change" },
        ],
        performanceBad: [
          { required: true, message: "请输入", trigger: "change" },
        ],
        performanceMt: [
          { required: true, message: "请输入", trigger: "change" },
        ],
      },
      categoryVisible: false,
      categoryList: [],
      loading: false,
      title: "",
      total: 0,
      CreateClienLoading: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        userId: "",
        performanceMoon: "",
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),

        // 上传的地址
        url: "",
      },

      timeSetLoading: false,
      uploadForm: {
        // moon: "",
        // editStatus: "N",
      },
      uploadRules: {
        // moon: [{ required: true, message: "请选择月份", trigger: "change" }],
      },

      userIdList: [],
      userIdLoading: false,
      seachUserTimeout: false,
      query: "",
    };
  },

  created() {
    this.getList();
    this.getUser(this.query);
  },

  mounted() {},

  methods: {
    remoteMethod(query) {
      console.log("输入要查询的值", query); // 输入要查询的值
      this.query = query;

      if (query !== "") {
        clearTimeout(this.seachUserTimeout);
        this.seachUserTimeout = setTimeout(() => {
          this.getUser(query);
        }, 500);
      } else {
        this.userIdList = [];
      }
    },
    getUser(query) {
      console.log(query, "关键字");

      listUser({
        pageNo: 1,
        pageSize: 20,
        keyword: query,
      }).then((response) => {
        console.log(response, "用户");
        this.userIdList = response.data.list;
      });
    },
    ProcessClose() {
      clearTimeout(this.Process);
      this.ProcessdialogVisible = false;
    },
    //
    ImportTemplate() {
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs["uploadForm"].validate((valid) => {
        if (valid) {
          const { moon, editStatus } = this.uploadForm;

          this.upload.url =
            process.env.VUE_APP_BASE_API +
            "/admin-api/store/performance/import";
          this.$nextTick(() => {
            this.LoadingIcon = this.$loading({
              lock: true,
              text: "数据导入中",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            this.$refs.upload.submit();
          });

          this.percentage = 0;
          this.ProcessdialogVisible = true;
          this.Process = setInterval(() => {
            this.percentage += 1;
            if (this.percentage >= 99) {
              clearTimeout(this.Process);
            }
          }, 1000);
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response, "response676712121");

      if (response.code !== 0) {
        this.LoadingIcon.close();
        this.ProcessClose();
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();

        this.$modal.msgError(response.msg);
        return;
      }

      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();

      this.timeSet = setInterval(() => {
        if (!this.timeSetLoading) {
          this.cx(response.data);
        }
      }, 1000);
    },
    handleFileError() {
      console.log("失败qwqw");
      this.LoadingIcon.close();
    },

    cx(token) {
      this.timeSetLoading = true;
      getFinishState({
        token,
      })
        .then((response) => {
          this.timeSetLoading = false;
          const { code, data } = response;
          if (code === 0) {
            if (data === "Y") {
              this.getList();
              clearInterval(this.timeSet);
              this.$alert("", "导入结果" + response.msg);
              this.ProcessClose();
              this.getimpFinishDown(token);
              this.LoadingIcon.close();
            }
          } else {
            clearInterval(this.timeSet);
            this.$alert("", "导入结果" + response.msg);
            this.ProcessClose();
          }
        })
        .catch((e) => {
          this.timeSetLoading = false;
          clearInterval(this.timeSet);
          this.$alert("", "导入结果" + e.msg);
          this.ProcessClose();
        });
    },

    getimpFinishDown(token) {
      ImportFinishDown({
        token,
      })
        .then((response) => {
          this.$download.excel(response, "导入结果.xls");
        })
        .catch(() => {});
    },

    uploadClose() {
      // 关闭弹窗
      this.upload.open = false;
      // 重置上传状态和文件
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();

      this.uploadForm.moon = "";
      this.uploadForm.editStatus = "N";
    },

    // 下载绩效考核导入模板
    DownloadTemplate() {
      DownTemplate()
        .then((response) => {
          this.$download.excel(response, "绩效考核导入模板.xls");
          this.$message({
            type: "success",
            message: "操作成功",
          });
        })
        .catch((err) => {});
    },

    // 获取详情
    getPerformance(performanceId) {
      getPerformancePageInfo({
        performanceId: performanceId,
      })
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.PerformanceForm.performanceId = data.performanceId;
            this.PerformanceForm.userId = data.userId;
            this.userIdList = [
              {
                id: data.userId,
                nickname: data.nickname,
              },
            ];
            this.PerformanceForm.performanceMoon = data.performanceMoon;
            this.PerformanceForm.performanceMt = data.performanceMt;
            this.PerformanceForm.performanceOnline = data.performanceOnline;
            this.PerformanceForm.performanceBad = data.performanceBad;
            this.PerformanceForm.performanceBy = data.performanceBy;
            this.PerformanceForm.performanceHire = data.performanceHire;
          }
        })
        .catch((err) => {});
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNo = 1;
      this.getLists();
    },

    // 店长考核绩效
    getList() {
      this.loading = true;
      getPerformancePage(this.queryParams)
        .then((res) => {
          this.loading = false;
          const { code, data } = res;
          if (code === 0) {
            this.categoryList = data.list;
            this.total = data.total;
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    Canceluser() {
      this.resetFormData("PerformanceForm");
      this.CreateClienLoading = false;
      this.$nextTick(() => {
        this.categoryVisible = false;
      });
    },

    // 筛选
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetFormData("queryForm");
      this.handleQuery();
    },

    // 新增类目
    userSubmit() {
      this.$refs["PerformanceForm"].validate((valid) => {
        console.log(this.PerformanceForm);
        if (valid) {
          if (!!this.PerformanceForm.performanceId) {
            this.UpdatePerformance();
          } else {
            this.CreatePerformance();
          }
        } else {
          return false;
        }
      });
    },

    // 新增
    CreatePerformance() {
      CreatePerformancePage(this.PerformanceForm)
        .then((res) => {
          const { code } = res;
          if (code === 0) {
            this.Canceluser();
            this.$message.success("操作成功");
            this.getList();
          }
        })
        .catch((err) => {});
    },

    // 编辑
    UpdatePerformance() {
      let PerformanceForm = JSON.parse(JSON.stringify(this.PerformanceForm));
      UpdatePerformancePage(PerformanceForm)
        .then((res) => {
          const { code } = res;
          if (code === 0) {
            this.Canceluser();
            this.$message.success("操作成功");
            this.getList();
          }
        })
        .catch((err) => {});
    },

    // 新建
    NewUser() {
      this.categoryVisible = true;
      this.title = "新增店长绩效考核";
      this.PerformanceForm.performanceId = "";
      this.getUser(this.query);
    },

    // 编辑类目
    edit(row) {
      this.categoryVisible = true;
      this.title = "编辑店长绩效考核";
      this.PerformanceForm.performanceId = row.performanceId;
      this.getPerformance(row.performanceId);
    },

    // 表单重置
    resetFormData(formName) {
      this.$refs[formName].resetFields();
    },

    // 删除用户
    DelUser(row) {
      this.$confirm("店长绩效考核删除后将无法撤回, 是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delPerformancePage({ performanceId: row.performanceId })
            .then((res) => {
              const { code } = res;
              if (code === 0) {
                this.getList();
                this.$modal.msgSuccess("操作成功");
              }
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.w-200 {
  width: 200px;
  background: #ffffff;
  border-radius: 4px;
}

.client_name {
  font-size: 14px;
  font-weight: 400;
  color: #0052d9;
}

.give {
  height: 40px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  margin-top: 40px;
  line-height: 40px;
}

.el-form-item {
  margin-bottom: 20px;
}

.recharge_form {
  padding: 10px 24px;
}

.memberName {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}
.el_row_item {
  margin-bottom: 10px;
}
.el_row_date {
  margin-top: 20px;
}
.el_row_reason {
  margin-top: 10px;
}

.el_row_date {
  .el-form-item {
    margin-bottom: 0px;
  }
}
.source_box {
  margin: 10px 24px;
}
</style>
